export default {
  data() {
    return {
      socket: null,
      reconnectionTimes: 0, // 重连次数
      maxReconnectionTimes: 3 // 最大重连次数
    }
  },
  methods: {
    setWebSocket(wsUrl, message_fun) {
      if(!this.socket) {
        this.socket = new WebSocket(wsUrl)
        this.socket.onopen = (res) => {
          // do something
        }
        this.socket.onmessage = (res) => {
          message_fun(JSON.parse(res.data))
        }
        this.socket.onerror = (res) => {
          if (this.reconnectionTimes < this.maxReconnectionTimes) {
            this.reconnectionTimes++
            console.error(`重连第${this.reconnectionTimes}次；`, res)
            this.socket = null
            this.setWebSocket(wsUrl, message_fun)
          } else {
            this.socket = null
          }
        }
        this.socket.onclose = (res) => {
          // do something
        }
      }
    },
    closeWebSocket() {
      if(this.socket) {
        this.socket.close()
        this.socket = null
      }
    }
  },
  beforeDestroy() {
    this.closeWebSocket()
  }
}